package cn.iocoder.ny.module.mall.controller.admin.pay;

import cn.hutool.core.io.IoUtil;
import cn.iocoder.ny.module.mall.domain.MallConfig;
import cn.iocoder.ny.module.mall.domain.MallConfigSimple;
import cn.iocoder.ny.module.mall.domain.vo.MallWeChatPayVo;
import cn.iocoder.ny.module.mall.service.*;
import cn.iocoder.ny.module.mall.service.impl.MallProductSpecificationSerivceImpl;
import cn.iocoder.ny.module.mall.utils.wxpay.AjaxResult;
import cn.iocoder.ny.module.mall.utils.wxpay.ResultModel;
import cn.iocoder.yudao.module.system.util.OkHttpUtils;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RSAPublicKeyNotificationConfig;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.core.util.GsonUtil;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付
 */
@RestController
@RequestMapping("v2pay")
public class MallPayController {

    private static final Logger log = LoggerFactory.getLogger(MallPayController.class);
//    public static String appId ="wx59d2c278e4e88df1";
//    public static String merchantId = "1680551706";
//    public static String privateKeyPath = "E:\\tuijingutil\\appdemo1\\pemfies\\apiclient_key_new.pem";
//    public static String merchantSerialNumber = "183169603A7ED47E743FC538BA8EDB7E279FA131";
//    public static String apiV3Key = "dnm5cz1mvyvfwkp4ngx45qtbv1zqrcbj";
//    String callurl = "https://2rz24qd15207.vicp.fun/api/ordercallback";


    public static String appId = "wxcb75b6c98bc58ec8";
    public static String merchantId = "1626020254";
    //public static String privateKeyPath = "E:\\tuijingutil\\appdemo1\\pemfies\\apiclient_key_new.pem";

    //public static String privateKeyPath = "/www/wwwroot/test1.01yingxiao.com/apiclient_key.pem";
    //223服务器
    //public static String privateKeyPath = "/www/wwwroot/test1.01yingxiao.com/apiclient_key.pem";
    public static String privateKeyString = "-----BEGIN PRIVATE KEY-----" +
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFJiAH8n60RvN3\n" +
            "Skk/P0g44Rx7pJaM5FdYJizTr/nsLvwHUQdBrBCnGUUGtegULD2eovFMRVK9qG8T\n" +
            "yvj6yrA3FsuvSVKqMpw9SBl4/pVdjy0eMQYHpUysRPxvxWC8633VD3Ut5l0H9kkI\n" +
            "kHwUA1AHkZ/Uts5KqtRnVlM2qUky4EHV0VjK7Cff3jB7aDn0puefOfNXoAHQmPoo\n" +
            "8dqEGOBcftycTof+4KTOme7rb1WlazoQVvPOAtb9dosM1j/rLqGGbZJPZowkpdfK\n" +
            "WuhFOSJLmsiaSVnOb58UJ/bE4exD+2eV5csCrnudKx7V8RhntLsjcl6X9mQi1HH/\n" +
            "PBr6vJMvAgMBAAECggEAbl15cPl/lMxjX1RmzNFQTQc4Or9YyGbLvr0gOyE4d8+V\n" +
            "p0LlHQ6GBAVRbwBGe4SIulXdXyUvvJyeEiZ+W2c8XpqUS/xwGndan7PNDr72Pvn3\n" +
            "9/7ZsU4ILigwaSHFlfz+5FdS8e8UBXEKUZEQ5OM12gbbwujTc1lOrsrUqrT6FVAa\n" +
            "Amjpq5dn3C6PY8OHXq8IhNmhqh9NF3qKG0ArFM2PikXFXCU64VSDaoXbA34IEsmL\n" +
            "bkJ4r9bpOv0QG2yzLpoqVlroIUrWZzUCz5wz+8RI5vxyLLNisa7dzW74fsyNprG8\n" +
            "ouWVgeq1jECmxDcdEPlfXz1n58gcWKLCB0+HYBj5gQKBgQDhn+6rJq/foIba+5If\n" +
            "t7P9KB5CsqJZZM5GvMqvUIX4XuDDN5Qwvgx7IpOW5LFYs0GdhjQsFXgOu+szJUwV\n" +
            "OpjLiP3OUuIsE0XJoJ9otzfawGIeNwMrb9jcw9Zvnt/fy9C+vggNudlB6y+VWmEy\n" +
            "1BGOSKgnLvY8MxskEgi6bTl0iwKBgQDfsMkHCX08KjITY8sVbASd9kF97o6+s9xU\n" +
            "X3csZRVjTYSJBjP74e97g4t/JfB7btuVrMKbKKK48pFoCJvQ9e9P5tkOesQSA6zL\n" +
            "7QFAMmYsVe4F+9pWTX8YFQ7VwvHF/9GLVjtZpUXSfMv0oIf2CynQzL7HZRfLtpF8\n" +
            "E7UBUqxcbQKBgQCvTJqcIb/N6SQ96e4bdJiEnfH88lvPRtI6BZ8Y3WBpnBXXt0wN\n" +
            "HuwFk9TGDUN5XjUh1c6dXcTc9caFA3p8l/11TieccatGgWbchE62hnwAGy9guG9f\n" +
            "BVSiGgp2ySK599plCLKrL3WMkNV0njcczcYiHXOAli08kpyIxvY/GnPkhwKBgAX5\n" +
            "/DUC7OSpn/LirK9i1nC9/pv1vrybo5xhfJakEME5dfwPPV5SeAqNxjFceyNhH97M\n" +
            "4doxaL+WQ4pLCJa5q24wFcaMQybUEE7Wgz0K2639kcF5LCk4Itgq392YOst2fUvC\n" +
            "vw0zHD12diCQFXHedHyOq9459jvMIfD1udVSNya1AoGAdHVbdExGuG/EAH21vmfQ\n" +
            "z9sCUAAzPnk9Q37B3cnDOSaWsNzfISj0kKzVLbpoSTbqSeMzJi+fDz8QNjHw/YtZ\n" +
            "z3F3bp1FIEWU08fKHu/KJSqGEAS5qHS3TK/MTbo3qwgJDa7r6PmgZ1lfFOoTCL3N\n" +
            "FNKjhYVF4YulDR8sWoA9WWE=\n" +
            "-----END PRIVATE KEY-----\n";
    public static String merchantSerialNumber = "76373E4E3C41E4CB0D46928DDEF8BE194AF82174";
    public static String apiV3Key = "a2aom2y0xgynhm435jdnmelfzgnr14vv";
    String callurl = "https://2rz24qd15207.vicp.fun/api/ordercallback";


//    //海豚商户号
//    public static String appId2 = "";
//    public static String merchantId2 = "1627539796";
//    public static String description2 = "商品";
//    public static String privateKeyString2 ="";
//    public static String merchantSerialNumber2="";
//    public static String apiV3Key2 = "";
//
//    public static String notifyUrl2 ="";


    @Autowired
    IMallWxPayService mallPayService;

    @Autowired
    private IMallOrderService mallOrderService;

    //    @Autowired
//    private IMallOrderDetailService mallOrderDetailService;
    @Autowired
    MallProductSpecificationSerivceImpl mallProductSpecificationSerivce;

    @Autowired
    IMallOrderService iMallOrderService;

    @Autowired
    IMallOrderDetailService iMallOrderDetailService;

    @Autowired
    IMallConfigService mallConfigService;


    @Autowired
    private RestTemplate restTemplate;

    private final IMallProductSpecificationSerivce iMallProductSpecificationSerivce;

    public MallPayController(IMallProductSpecificationSerivce iMallProductSpecificationSerivce) {
        this.iMallProductSpecificationSerivce = iMallProductSpecificationSerivce;
    }


    @RequestMapping("/postman01")
    public AjaxResult postman01(@RequestBody HashMap<String, Object> hashMap) {
        log.info("postman01 入参是:" + JSON.toJSONString(hashMap));
        return AjaxResult.success(hashMap);
    }


    /**
     * 微信小程序单
     *
     * @return
     */
    @RequestMapping("/prepayByJsapi")
    public AjaxResult prepayByJsapi(@RequestBody MallWeChatPayVo vo) {
        log.info("preorder 入参是:" + JSON.toJSONString(vo));

        return AjaxResult.success(mallPayService.prepayByJsapi(vo));
    }


    //测试新部署的退款服务
    @PermitAll
    @RequestMapping("/fakeuser")
    public HashMap<String, Object> fakeuser(@RequestBody HashMap<String, Object> hashMap) {
        hashMap.put("version", "01");
        log.info("fakeuser {}", JSON.toJSONString(hashMap));

        return AjaxResult.success(hashMap);
    }

    //测试新部署的退款服务
    @PermitAll
    @RequestMapping("/fakeversion")
    public HashMap<String, Object> fakeversion(@RequestBody HashMap<String, Object> hashMap) {
        hashMap.put("version", "01");
        log.info("fakeuser {}", JSON.toJSONString(hashMap));

        return AjaxResult.success(hashMap);
    }


    //提供服务
    @PermitAll
    @RequestMapping("/apimerchant")
    public MallConfigSimple apimerchant(@RequestBody MallConfig mallConfig) {
        //通过aid pid
//        String s_aid = inmap.get("aid").toString();
//        int aid = Integer.parseInt(s_aid);
//
//        String s_pid = inmap.get("pid").toString();
//        int pid = Integer.parseInt(s_pid);

        MallConfig one = mallConfigService.lambdaQuery().eq(MallConfig::getAId, mallConfig.getAId())
                .eq(MallConfig::getPId, mallConfig.getPId()).one();
        //访问 一坨数据应该是json

        MallConfigSimple mallConfigSimple = new MallConfigSimple();
        //mallConfigSimple.setAid(one.getAId());
        mallConfigSimple.setMch_id(one.getMchId());
        mallConfigSimple.setApi_v3_key(one.getApiV3Key());
        mallConfigSimple.setPrivate_key(one.getPrivateKey());
        mallConfigSimple.setMch_serial_number(one.getMchSerialNumber());
        //mallConfigSimple.setAppid(one.getAppid());


        return mallConfigSimple;
    }


    //测试用
    @PermitAll
    @RequestMapping("/newNotify")
    public String newNotify(@RequestBody HashMap<String, Object> inmap) {
        log.info("newNotify {}", JSON.toJSONString(inmap));
        //String url = "https://mpt.zcqhkj.cn/app/index.php?i=2&c=entry&do=api_pay_result";
        //String url = "https://mpt.zcqhkj.cn/app/index.php?i=2&c=entry&do=api_pay_result&m=water_salegroup3";
        String url = "https://mpt.zcqhkj.cn/app/index.php?i=2&c=entry&do=api_pay_result&m=water_salegroup3&tid=122&fee=123&openid=123&transaction_id=1122";
        HashMap<String, Object> pinmap = new HashMap<>();
        pinmap.put("tid", 12312);
        pinmap.put("fee", 0.01);
        pinmap.put("openid", "abc");
        pinmap.put("transaction_id", 12313123);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, pinmap, String.class);
        String confighttp = responseEntity.getBody();

        return confighttp;
    }

    //测试夏天
    //测试用
    @PermitAll
    @RequestMapping("/findshopfromoa")
    public String findshopfromoa(@RequestBody HashMap<String, Object> inmap) {
        log.info("findshopfromoa {}", JSON.toJSONString(inmap));
        String dedeurl = "https://oa.cmzg.vip/api/order/pay/wx";
        ResponseEntity<String> responseEntity2 = restTemplate.postForEntity(dedeurl, inmap, String.class);
        return responseEntity2.getBody().toString();
    }

    //测试用
    @PermitAll
    @RequestMapping("/dede")
    public String dede(@RequestBody String inmap) {
        log.info("dede {}", inmap);

        return JSON.toJSONString(inmap);
    }


    //测试用
    @PermitAll
    @RequestMapping("/sendtodede")
    public String sendtodede(@RequestBody HashMap<String, Object> inmap) {
        log.info("sendtodede {}", JSON.toJSONString(inmap));

        //String dedeurl = "https://2rz24qd15207.vicp.fun/admin-api/v2pay/dede";
        String dedeurl = "https://nysaas.mynatapp.cc/admin-api/v2pay/dede";
        HashMap<String, Object> demap = new HashMap<>();
        demap.put("retursss", "string");
        ResponseEntity<String> responseEntity2 = restTemplate.postForEntity(dedeurl, demap, String.class);
        String confighttp = responseEntity2.getBody();

        MallConfigSimple mallConfigSimple = JSON.parseObject(confighttp, MallConfigSimple.class);
        return confighttp;
    }


    @PermitAll
    @RequestMapping("/mppay")
    public ResultModel mppay(@RequestBody HashMap<String, Object> inmap) {
        log.info("mppay {}", JSON.toJSONString(inmap));
        ResultModel<PrepayWithRequestPaymentResponse> resultModel = new ResultModel<>();
        //check

        MallConfigSimple mallConfigSimple = getConfigOA(inmap);

        if (mallConfigSimple.getMch_id() == null) {
            resultModel.setIsSuccess(false);
            resultModel.setCode("lgerror");
            return resultModel;
        } else {

            log.info("oamap {}", JSON.toJSONString(mallConfigSimple));
        }


        //第一部分post
        String merchantId2 = mallConfigSimple.getMch_id();
        String privateKeyString2 = mallConfigSimple.getPrivate_key();
        String merchantSerialNumber2 = mallConfigSimple.getMch_serial_number();
        String apiV3Key2 = mallConfigSimple.getApi_v3_key();
        //appId2 = mallConfigSimple.getAppid();

        //第二部分前端
        String appId2 = inmap.get("appid2").toString();
        String aid = inmap.get("aid2").toString();
        String pid = inmap.get("pid2").toString();
        //String outTradeNo2 = inmap.get("orderid2").toString();
        String s_total2 = inmap.get("total2").toString(); //0.01
        //tid
        String tid2 = inmap.get("tid2").toString(); //0.01


        BigDecimal bd = new BigDecimal(s_total2);

        // 乘以 100 转换为分
        BigDecimal bdInCents = bd.multiply(new BigDecimal("100"));

        // 设置小数位数为0，并指定四舍五入模式，避免精度问题
        bdInCents = bdInCents.setScale(0, RoundingMode.DOWN);

        // 转换为 Integer 类型
        int total2 = bdInCents.intValue();

        String openid2 = inmap.get("openid2").toString();


        //回调
        //用test1 SAAS
        //String paynotifyurl = "https://test1.01yingxiao.com/admin-api/v2pay/notify/payNotify/";
        //String paynotifyurl = "http://2rz24qd15207.vicp.fun/admin-api/v2pay/notify/payNotify/";

        String paynotifyurl = "https://secondpay.cmzg.vip/admin-api/v2pay/notify/payNotify/";
        //
        // 第二台服务器
        // String paynotifyurl = "https://secondpaybackup.cmzg.vip/admin-api/v2pay/notify/payNotify/";

        //String paynotifyurl = "https://nysaas.mynatapp.cc/admin-api/v2pay/notify/payNotify/";


        RSAPublicKeyConfig config2 = null;
        String gong = null;
        String gongid = null;
        if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode().toString())) {
            gong = mallConfigSimple.getPubkey_pem();
            gongid = mallConfigSimple.getPubkey_id();
            config2 = new RSAPublicKeyConfig.Builder()
                    .merchantId(merchantId2)
                    .privateKey(privateKeyString2)
                    .merchantSerialNumber(merchantSerialNumber2)
                    .publicKey(gong)
                    .publicKeyId(gongid)
                    .apiV3Key(apiV3Key2)
                    .build();
        }

        //String notifyUrl2 = paynotifyurl + appId2 + "/" + aid + "/" + pid + "/" + outTradeNo2;
        String notifyUrl2 = paynotifyurl + appId2 + "/" + aid + "/" + pid + "/" + tid2;
        log.info("支付回到{}", notifyUrl2);
        JsapiServiceExtension service = null;
        // 构建service
        try {
            if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode())) {
                service = new JsapiServiceExtension.Builder().config(config2).build();
            } else {
                RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId2)
                        .privateKey(privateKeyString2)
                        .merchantSerialNumber(merchantSerialNumber2)
                        .apiV3Key(apiV3Key2)
                        .build();
                service = new JsapiServiceExtension.Builder().config(config).build();
            }
        } catch (Exception ex) {
            resultModel.setIsSuccess(false);
            resultModel.setCode("lgerror2");
            return resultModel;
        }

        // 构建service

        //构建请求
        PrepayRequest request = new PrepayRequest();
        //基础信息
        request.setAppid(appId2);
        request.setMchid(merchantId2);
        request.setDescription("门店服务");//商品描述
        //前端
//        request.setOutTradeNo(outTradeNo2);//商户系统内部订单号
        request.setOutTradeNo(tid2);//商户系统内部订单号

        HashMap<String, Object> attachmap2 = new HashMap<>();
        attachmap2.put("tid", tid2);
        attachmap2.put("fee", s_total2);
        attachmap2.put("iii", inmap.get("pid2").toString());

        String jsonString = JSON.toJSONString(attachmap2);
        log.info("查看支付attach的string对象{}", jsonString);


        request.setAttach(jsonString);//附加数据
        request.setNotifyUrl(notifyUrl2);
        //订单金额信息
        Amount amount = new Amount();
        //前端金额
        amount.setTotal(total2);
        request.setAmount(amount);
        //用户在直连商户appid下的唯一标识。 下单前需获取到用户的Openid
        Payer payer = new Payer();
        //前端
        payer.setOpenid(openid2);
        request.setPayer(payer);
        try {
            PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
            log.info("JSAPI下单-结果：{}", response.toString());
            resultModel.setIsSuccess(true);
            resultModel.setData(response);
        } catch (Exception ex) {
            //setException(resultModel, ex);
            resultModel.setIsSuccess(false);
            resultModel.setCode("lgerror");

        }
        log.info("JSAPI下单-结束：{}", com.alibaba.fastjson.JSON.toJSONString(resultModel));
        return resultModel;
    }


    //原名autorefund
    //小周用39like  来退款（微信需要tid  和   冬月需要39）
    @PermitAll
    @RequestMapping("/mprefund")
    public HashMap<String, Object> mprefund(@RequestBody HashMap<String, Object> inmap) {
        log.info("mprefund {}", JSON.toJSONString(inmap));
        //小周拿着39来退款。 我要通过39查tid
        HashMap<String, Object> rtoui = new HashMap<>();
        String s39like = inmap.get("orderid2").toString();  //


        String orderNo = null;
        try {
            orderNo = getTidbys39(s39like).get("key");  // 用xitong的 tid去退款
        } catch (Exception e) {
            //大屏服务 DB问题
            orderNo = "02025011517220836932928308774";
            rtoui.put("msg", "php没有找到tid");
            rtoui.put("code", "e010");
            return rtoui;
        }

        if (orderNo == null || orderNo.isEmpty()) {
            rtoui.put("flag", "error");
            rtoui.put("msg", "没有找到tid");
            rtoui.put("code", "e009");
            return rtoui;
        }
        String uireason = inmap.get("reason").toString();

        log.info("申请退款-开始");

        ResultModel<Refund> resultModel = new ResultModel<>();


        // 构建service
        //ResultModel<PrepayWithRequestPaymentResponse> resultModel = new ResultModel<>();
        MallConfigSimple mallConfigSimple = getConfigOAOld(inmap);
        if (mallConfigSimple.getMch_id() == null) {
            resultModel.setIsSuccess(false);
            resultModel.setCode("lgerror");
            rtoui.put("code", "e007");
            rtoui.put("msg", "支付信息不对");
            return rtoui;
        }

        //第一部分post
        String merchantId2 = mallConfigSimple.getMch_id();
        String privateKeyString2 = mallConfigSimple.getPrivate_key();
        String merchantSerialNumber2 = mallConfigSimple.getMch_serial_number();
        String apiV3Key2 = mallConfigSimple.getApi_v3_key();


        //微信公钥模式支付的退款

        RSAPublicKeyConfig config2 = null;
        String gong = null;
        String gongid = null;
        if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode().toString())) {
            gong = mallConfigSimple.getPubkey_pem();
            gongid = mallConfigSimple.getPubkey_id();
            config2 = new RSAPublicKeyConfig.Builder()
                    .merchantId(merchantId2)
                    .privateKey(privateKeyString2)
                    .merchantSerialNumber(merchantSerialNumber2)
                    .publicKey(gong)
                    .publicKeyId(gongid)
                    .apiV3Key(apiV3Key2)
                    .build();
        }

        //uitodo
        //String notifyUrl2 = paynotifyurl + appId2 + "/" + aid + "/" + pid + "/" + outTradeNo2;

        //第二部分前端
        String appId2 = inmap.get("appid2").toString();
        String aid = inmap.get("aid2").toString();
        String pid = inmap.get("pid2").toString();
        String outTradeNo2 = inmap.get("orderid2").toString();      //其实就是39like; 因为aid pid 的原因 短的39like 不会重复
        String s_total2 = inmap.get("total2").toString(); //0.01
        String openid2 = inmap.get("openid2").toString();
        String baserefund = "https://secondpay.cmzg.vip/admin-api/v2pay/notify/refundNotify/";
        //String baserefund = "https://2rz24qd15207.vicp.fun/admin-api/v2pay/notify/refundNotify/";
        String refundurl = baserefund + appId2 + "/" + aid + "/" + pid + "/" + outTradeNo2 + "/" + s_total2 + "/" + openid2;

        log.info("退款回到 url-{}", refundurl);
        //新的退款
        RefundService service = null;

        if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode().toString())) {
            log.info("新模式退款");
            //if (false) {
            service = new RefundService.Builder().config(config2).build();
        } else {
            RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId2)
                    //.privateKey(mallConfig.getPrivateKey())
                    //.privateKeyFromPath("E:\\tuijingutil\\appdemo1\\src\\main\\resources\\apiclient_key.pem")
                    .privateKey(privateKeyString2)
                    .merchantSerialNumber(merchantSerialNumber2)
                    .apiV3Key(apiV3Key2)
                    .build();
            service = new RefundService.Builder().config(config).build();
        }


        // return wxPayUtil.refundsByOutTradeNo(vo.getOrderNo(), vo.getOutRefundNo(), vo.getTotal(), vo.getRefund(), NotifyUrlUtil.getRefundNotifyUrl(vo));
        //构建请求
        CreateRequest request = new CreateRequest();
        //request.setOutTradeNo(outTradeNo);
        request.setOutTradeNo(orderNo);
        request.setOutRefundNo("R" + orderNo); //退款单号，切记别随机
        //request.setNotifyUrl(refundNotifyUrl);
        //request.setNotifyUrl("https://2rz24qd15207.vicp.fun/notify/refundNotify/wxcb75b6c98bc58ec8/"+orderNo);
        //request.setNotifyUrl("https://test2.01yingxiao.com/notify/refundNotify/wxcb75b6c98bc58ec8/" + orderNo);
        request.setNotifyUrl(refundurl);

        //金额信息
        //第二部分UI 传我退款信息,  long refundAmount =  inmap.get("m2");  //钱1 最好是分
        //long refundAmount = Long.parseLong( inmap.get("m2").toString());   //s_total2
        //long refundAmount = Long.parseLong( s_total2 );
        // long refundTotal  = inmap.get("mt2");  //钱2
        //long refundTotal = Long.parseLong( inmap.get("mt2").toString());
        //long refundTotal = Long.parseLong( s_total2);


        BigDecimal bd = new BigDecimal(s_total2);
        BigDecimal bdInCents = bd.multiply(new BigDecimal("100"));
        bdInCents = bdInCents.setScale(0, RoundingMode.DOWN);
        int total2 = bdInCents.intValue();

        AmountReq amountReq = new AmountReq();
        amountReq.setRefund((long) total2); //退款金额
        amountReq.setTotal((long) total2);  //退款金额


        amountReq.setCurrency("CNY");
        request.setAmount(amountReq);
        request.setReason(uireason);  //退款理由

        try {
            service.create(request);
            resultModel.setIsSuccess(true);
        } catch (Exception ex) {
            //setException(resultModel, ex);
            log.info("异常过");
            log.info(JSON.toJSONString(ex));
            rtoui.put("flag", "yichang");
            rtoui.put("code", "e008");
            rtoui.put("yichang", JSON.toJSONString(ex));
            return rtoui;
        }
        log.info("申请退款-结束：{}", JSON.toJSONString(resultModel));
        rtoui.put("flag", "ok");
        rtoui.put("data", resultModel);
        return rtoui;

    }

    //查询订单
    @PermitAll
    @RequestMapping("/fakefind")
    public HashMap<String, Object> fakefind(@RequestBody HashMap hashMapin) {
        String orderNo = hashMapin.get("orderNo").toString();
        //---------------wxutil--------begin-----
        log.info("查询订单-商户订单号查询-开始");
        ResultModel<Transaction> resultModel = new ResultModel<>();
        // 构建service
        //构建请求

        RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                .privateKey(privateKeyString)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3Key)
                .build();

        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();

        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        request.setMchid(merchantId);
        request.setOutTradeNo(orderNo);
        HashMap<String, Object> hashMap = new HashMap<>();
        try {
            Transaction transaction = service.queryOrderByOutTradeNo(request);
            resultModel.setIsSuccess(true);
            resultModel.setData(transaction);
        } catch (Exception ex) {
            //setException(resultModel, ex);

            //return null; //spring boot 可能会报错；因为前端要求会转json
            hashMap.put("yichang", JSON.toJSONString(ex));
        }
        log.info("查询订单-商户订单号查询-结束：{}", JSON.toJSONString(resultModel));
        //-------------wxutil---------end

        hashMap.put("flag", "ok");
        hashMap.put("data", resultModel);

        return hashMap;
    }


    /**
     * 支付回调
     */
    @PermitAll
    @RequestMapping("/notify/payNotify/{appId}/{aid}/{pid}/{orderNo}")
    public ResultModel<Transaction> payNotify(HttpServletRequest request, @PathVariable("pid") String pid, @PathVariable("aid") String aid, @PathVariable("appId") String appId, @PathVariable("orderNo") String orderNo) {
        log.info("支付回调lg {}-{}-{}-{}", appId, aid, pid, orderNo);
        log.info("支付通知-开始");
        //todo need inmap

        HashMap<String, Object> inmap = new HashMap<>();
        inmap.put("aid2", aid);
        inmap.put("pid2", pid);
        MallConfigSimple mallConfigSimple = getConfigOA(inmap);
        //第一部分post
        String merchantId2 = mallConfigSimple.getMch_id();
        String privateKeyString2 = mallConfigSimple.getPrivate_key();
        String merchantSerialNumber2 = mallConfigSimple.getMch_serial_number();
        String apiV3Key2 = mallConfigSimple.getApi_v3_key();

        NotificationConfig config2 = null;
        if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode().toString())) {
            config2 = new RSAPublicKeyNotificationConfig.Builder()
                    .publicKey(mallConfigSimple.getPubkey_pem())
                    .publicKeyId(mallConfigSimple.getPubkey_id())
                    .apiV3Key(apiV3Key2)
                    .build();
        }

        ResultModel<Transaction> resultModel = new ResultModel<>();

        try {
            String body = IoUtil.getUtf8Reader(request.getInputStream()).readLine();
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    .signature(request.getHeader("Wechatpay-Signature"))
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .signType(request.getHeader("Wechatpay-Signature-Type"))
                    .body(body)
                    .build();

            NotificationParser parser = null;
            if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode())) {
                parser = new NotificationParser(config2);
            } else {
                RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId2)
                        .privateKey(privateKeyString2)
                        .merchantSerialNumber(merchantSerialNumber2)
                        .apiV3Key(apiV3Key2)
                        .build();
                parser = new NotificationParser(config);
            }
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            //-----------------------支付成功通知
            String openid = transaction.getPayer().getOpenid();
            String qjson = transaction.getAttach();

            //修改 把sq变成sqjson
            log.info("购买的库存sqjson：" + qjson);
            // 使用 Fastjson 解析 JSON 字符串到 Map
            Map<String, Object> map = JSON.parseObject(qjson, Map.class);
            log.info("Map-结束：{}", JSON.toJSONString(map));
            String tid = map.get("tid").toString();
            String fee = map.get("fee").toString();
            String iii = map.get("iii").toString();
            // 输出 Map 中的内容
            if (map != null) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                }
            }
            //todo 调董的接口1
            //todo 调董的接口2

            String transaction_id = transaction.getTransactionId();

            String url = "https://cm.cmzg.vip/app/index.php?i=" +
                    iii + "&c=entry&do=api_pay_result&m=water_salegroup3&tid=" +
                    tid + "&fee=" +
                    fee + "&openid=" +
                    openid + "&transaction_id=" + transaction_id;

            //支付成功 todo 1更改订单状态 支付时间
            //支付成功 todo 2更改详情状态。
            log.info("冬月的支付url {}", url);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String confighttp = responseEntity.getBody();

            //String dedeurl = "https://2rz24qd15207.vicp.fun/admin-api/v2pay/dede";
//            String dedeurl = "https://nysaas.mynatapp.cc/admin-api/v2pay/dede";
//            HashMap<String,Object> demap3 = new HashMap<>();
//            demap3.put("返回数据",confighttp);
//            ResponseEntity<String> responseEntity3 = restTemplate.postForEntity(dedeurl,demap3,String.class);

//            HashMap<String,Object> demap4 = new HashMap<>();
//            demap4.put("todong",confighttp);
//            ResponseEntity<String> responseEntity4 = restTemplate.postForEntity(dedeurl,demap4,String.class);


            log.info("夏天oa的新订单开始");
            String dytid2 = orderNo;
            String dbw2_tid2_ordersn = dytid2.substring(1);
            Integer detailid = findOrderBytid2(dbw2_tid2_ordersn);
            updateNewOrderbyNid("1"+detailid); //拼团是1  方案1
            //updateNewOrderbyTid2(dytid2);  //方案2  不要用
            log.info("夏天oa的新订单结束");


            //--------------------支付成功结束
            resultModel.setIsSuccess(true);
            resultModel.setData(transaction);

        } catch (Exception ex) {
            log.info("异常aaa：{}", GsonUtil.getGson().toJson(ex));
            //setException(resultModel, ex);
        }

        //通知夏天?
        //方案一 getphp(通知下大屏php) 让php通知夏天
        //方案二 直接java 通知夏天
        try {

            //User user = new User("John", "john_new@example.com");

            Map<String, Object> params = new HashMap<>();
            params.put("order", "order");
            // 本来是这样 http://example.com/users/{id}
            // 夏天的是这样

            //restTemplate.put("http://example.com/users/{id}", user, params);
        } catch (Exception ex) {
            //log.info("夏天一次：{}", GsonUtil.getGson().toJson(resultModel));
        }

        log.info("支付通知-结束：{}", GsonUtil.getGson().toJson(resultModel));
        return resultModel;
    }

    @PermitAll
    @RequestMapping("/api/shoudong01")
    public ResponseEntity shoudong01() {
        //Nid 等于 1 + detailid 或者 2+ detailid
        //冬月的ti2d 找到 db_detailid
        String ti2 = "22024111011540631210846938948";
        String dbw2_tid2_ordersn = ti2.substring(1);
        Integer detailid = findOrderBytid2(dbw2_tid2_ordersn);
        updateNewOrderbyNid("1"+detailid);
        return null;
    }

    //手动测试 夏天的修改代码
    @PermitAll
    @RequestMapping("/api/shoudong02")
    public ResponseEntity shoudong02(String nid) {
        log.info("shoudong02");
        updateNewOrderbyNid(nid);
        // 02025051410300847189808168257   02025051410050647188306874667
        //updateNewOrderbyDYTid2("02025051410300847189808168257");   夏天接口有问题 不要用
        return null;
    }


    @PermitAll
    @RequestMapping("/api/luoming")
    public ResponseEntity luoming() {
        log.info("luoming");
        log.info("luoming");
        return null;
    }

    ////todo 通过tid2...因为支付是通过tid2的。  但是oa 【新订单】记录的是detailid
    public void updateNewOrderbyNid(String Nid) {
        try {
            //User user = new User("John", "john_new@example.com");
            Map<String, Object> params = new HashMap<>();
            params.put("order", "order");
            // 本来是这样 http://example.com/users/{id}
            // 夏天的是这样 https://gateway.cmxz.com.cn/oa/api/new/order/
            String xia = "https://gateway.cmxz.com.cn/oa/api/new/{userId}/";   //当然也可以last = "order"
            // URI变量映射
            Map<String, String> uriVariables = new HashMap<>();
            uriVariables.put("userId", "order"); // 替换 {userId} 占位符

            // 使用 Map 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("nid", Nid);
            //requestBody.put("option5", "xg");
            requestBody.put("status_pay", 1);
            restTemplate.put(xia,requestBody ,uriVariables);
        } catch (Exception ex) {
            log.info(JSON.toJSONString(ex));
        }
    }

    public void updateNewOrderbyDYTid2(String dytid2) {
        try {
            //dytid2

            //https://gateway.cmxzcom.cn/oa/api/new/updateneworderbyditd2/

            //User user = new User("John", "john_new@example.com");

            String xia = "https://gateway.cmxz.com.cn/oa/api/new/{userId}/";   //当然也可以last = "order"
            // URI变量映射
            Map<String, String> uriVariables = new HashMap<>();
            uriVariables.put("userId", "updateneworderbyditd2"); // 替换 {userId} 占位符

            // 使用 Map 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("dytid2", dytid2);
            //requestBody.put("option3", "John Doe");
            requestBody.put("status_pay", 1);
            restTemplate.put(xia,requestBody ,uriVariables);
        } catch (Exception ex) {
            log.info(JSON.toJSONString(ex));
        }
    }

    @PermitAll
    @RequestMapping("/health")
    public HashMap health() {
        //http://localhost:4003/admin-api/v2pay/health
        HashMap<String, Object> r = new HashMap<>();
        r.put("code", 200);
        r.put("msg", "成功");
        return r;
    }


    //https://2rz24qd15207.vicp.fun
    @RequestMapping("/api/ordercallback")
    public ResultModel<Transaction> ordercallback(HttpServletRequest request) {
        ResultModel<Transaction> resultModel = new ResultModel<>();

        try {
            String body = IoUtil.getUtf8Reader(request.getInputStream()).readLine();

            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    .signature(request.getHeader("Wechatpay-Signature"))
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .signType(request.getHeader("Wechatpay-Signature-Type"))
                    .body(body)
                    .build();

            //todo 我怎么知道是这个merchantid  或者 wxappid
            RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId)
                    //.privateKey(mallConfig.getPrivateKey())
                    //.privateKeyFromPath("E:\\tuijingutil\\appdemo1\\src\\main\\resources\\apiclient_key.pem")
                    .privateKeyFromPath("E:\\tuijingutil\\appdemo1\\apiclient_key_new.pem")
                    .merchantSerialNumber(merchantSerialNumber)
                    .apiV3Key(apiV3Key)
                    .build();

            NotificationParser parser = new NotificationParser(config);


            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            resultModel.setIsSuccess(true);
            resultModel.setData(transaction);
        } catch (Exception ex) {
            //setException(resultModel, ex);
            resultModel.setCode("lgerror");
            return resultModel; //spring boot 可能会报错；因为前端要求会转json
        }
        log.info("支付通知-结束：{}", JSON.toJSONString(resultModel));
        return resultModel;
    }


    /**
     * 根据订单号查询支付结果
     *
     * @param vo
     * @return
     */
    @RequestMapping("/queryByOutTradeNo")
    public AjaxResult queryByOutTradeNo(@RequestBody MallWeChatPayVo vo) {
        return AjaxResult.success(mallPayService.queryByOutTradeNo(vo));
    }

    /**
     * 关闭订单
     *
     * @param vo
     * @return
     */
    @RequestMapping("/closeByOutTradeNo")
    public AjaxResult closeByOutTradeNo(@RequestBody MallWeChatPayVo vo) {
        return AjaxResult.success(mallPayService.closeByOutTradeNo(vo));
    }

    /**
     * 退款
     *
     * @param vo
     * @return
     */
    @RequestMapping("/refundsByOutTradeNo")
    public AjaxResult refundsByOutTradeNo(@RequestBody MallWeChatPayVo vo) {
        //真的退款 要组装退款的数据 例如 退款金额
        //
        return AjaxResult.success(mallPayService.refundsByOutTradeNo(vo));
    }

    @RequestMapping("/agreeToRefund")
    public AjaxResult agreeToRefund(@RequestBody MallWeChatPayVo vo) {
        //真的退款 要组装退款的数据 例如 退款金额
        log.info("agreeToRefund入参：{}", JSON.toJSONString(vo));
        return AjaxResult.success(mallPayService.refundsByOutTradeNo(vo));
    }


    /**
     * 退款通知{appId}/{aid}/{pid}/{orderNo}
     */
    @PermitAll
    @RequestMapping("/notify/refundNotify/{appId}/{aid}/{pid}/{orderNo}/{fee}/{openid}")
    public Map<Object, Object> refundNotify(HttpServletRequest request, @PathVariable("pid") String pid, @PathVariable("aid") String aid, @PathVariable("appId") String appId, @PathVariable("orderNo") String orderNo, @PathVariable("fee") String fee, @PathVariable("openid") String openid) {
        log.info("fun-refundNotify {}-{}-{}-{}-{}-{}", appId, aid, pid, orderNo, fee, openid);
        Map<Object, Object> r = new HashMap<>();
        //注意这个 ordernNo 就是39like
        HashMap<String, Object> inmap = new HashMap<>();
        inmap.put("aid2", aid);
        inmap.put("pid2", pid);
        MallConfigSimple mallConfigSimple = getConfigOA(inmap);

        log.info("退款结果通知-开始");
        ResultModel<RefundNotification> resultModel = new ResultModel<>();
        //第一部分post
        String merchantId2 = mallConfigSimple.getMch_id();
        String privateKeyString2 = mallConfigSimple.getPrivate_key();
        String merchantSerialNumber2 = mallConfigSimple.getMch_serial_number();
        String apiV3Key2 = mallConfigSimple.getApi_v3_key();

        NotificationConfig config2 = null;
        if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode().toString())) {
            config2 = new RSAPublicKeyNotificationConfig.Builder()
                    .publicKey(mallConfigSimple.getPubkey_pem())
                    .publicKeyId(mallConfigSimple.getPubkey_id())
                    .apiV3Key(apiV3Key2)
                    .build();
        }

        try {
            String body = IoUtil.getUtf8Reader(request.getInputStream()).readLine();
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial"))
                    .nonce(request.getHeader("Wechatpay-Nonce"))
                    .signature(request.getHeader("Wechatpay-Signature"))
                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .signType(request.getHeader("Wechatpay-Signature-Type"))
                    .body(body)
                    .build();
            NotificationParser parser = null;
            if ("2".equalsIgnoreCase(mallConfigSimple.getPay_mode())) {
                parser = new NotificationParser(config2);
            } else {
                RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId2)
                        .privateKey(privateKeyString2)
                        .merchantSerialNumber(merchantSerialNumber2)
                        .apiV3Key(apiV3Key2)
                        .build();
                parser = new NotificationParser(config);
            }

            RefundNotification refundNotification = parser.parse(requestParam, RefundNotification.class);

            //https://developers.weixin.qq.com/miniprogram/dev/wxcloudservice/wxcloudrun/src/development/pay/order/refund.html
            String transaction_id = refundNotification.getTransactionId();
            Long wxfee = refundNotification.getAmount().getTotal();  //明显是WXfee 比我们的大100倍
            refundNotification.getRefundStatus();
            //退款成功后
            log.info("测试下OA----begin");


            if (refundNotification.getRefundStatus().equals(Status.SUCCESS)) {
                toNotifyOA(appId, aid, pid, orderNo, fee, openid, "1", "");
            } else {
                toNotifyOA(appId, aid, pid, orderNo, fee, openid, "2", "处-理-中");
            }

            log.info("测试下OA----end");


            //钱怎么传过来
            String url = "https://cm.cmzg.vip/app/index.php?i=" +
                    pid + "&c=entry&themeid=" +
                    aid + "&do=api_record_refund&m=water_salegroup3&recordid=" +
                    orderNo + "&fee=" +
                    fee;


//            String url ="http://back.screen.cmxz.com.cn/index/secondpayrefund?i" +
//                    pid +"&c=entry&themeid=" +
//                    aid +"&do=api_record_refund&m=water_salegroup3&recordid=" +
//                    orderNo +"&fee=" +
//                    fee ;

            log.info("系统通知退款的url {}", url);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            String confighttp = responseEntity.getBody();

            log.info("系统通知OA退款url {}", url);

            HashMap<String, Object> demap4 = new HashMap<>();
            demap4.put("todong", confighttp);
            String dedeurl = "https://2rz24qd15207.vicp.fun/admin-api/v2pay/dede";
            //ResponseEntity<String> responseEntity4 = restTemplate.postForEntity(dedeurl,demap4,String.class);

            resultModel.setIsSuccess(true);
            resultModel.setData(refundNotification);
        } catch (Exception ex) {
            //setException(resultModel, ex);
            log.info("退款通知异常" + GsonUtil.getGson().toJson(ex));
            r.put("msg", "异常");
            r.put("code", "e001");
            toNotifyOA(appId, aid, pid, orderNo, fee, openid, "2", GsonUtil.getGson().toJson(ex));
            return r;
        }
        log.info("退款结果通知-结束：{}", GsonUtil.getGson().toJson(resultModel));

        r.put("msg", "正常结束2");
        r.put("code", "s001");

        return r;
    }

    /**
     * 查询退款
     *
     * @param vo
     * @return
     */
    @RequestMapping("/refundsQueryByOutRefundNo")
    public AjaxResult refundsQueryByOutRefundNo(@RequestBody MallWeChatPayVo vo) {

        return AjaxResult.success(mallPayService.refundsQueryByOutRefundNo(vo));
    }


    //agreeToRefund 真的退款
    public static String removeNewLines(String input) {
        if (input == null) {
            return null;
        }
        // 使用 replaceAll 方法来移除所有的换行符。
        // 如果你还想移除回车符 \r，你可以使用相同的逻辑。
        return input.replaceAll("\\n", "");
    }

    public MallConfigSimple getConfigOA(HashMap<String, Object> inmap) {

        String url = null; //180DB 硬塞
        if (inmap.containsKey("test")) {
            url = "https://test1.01yingxiao.com/admin-api/v2pay/apimerchant";
        } else {
            //url = "https://oa.cmzg.vip/api/order/pay/wx";
            url = "https://gateway.cmxz.com.cn/oa/api/order/pay/wx";
        }

        HashMap<String, Object> postmap = new HashMap<>();
        postmap.put("aid", inmap.get("aid2").toString());
        postmap.put("pid", inmap.get("pid2").toString());

        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, postmap, String.class);
        } catch (Exception e) {
            log.info("异常");
        }


        String confighttp = responseEntity.getBody();
        MallConfigSimple mallConfigSimple = JSON.parseObject(confighttp, MallConfigSimple.class);
        return mallConfigSimple;
    }

    //getConfigOAOld
    public MallConfigSimple getConfigOAOld(HashMap<String, Object> inmap) {

        String url = null; //180DB 硬塞
        if (inmap.containsKey("test")) {
            url = "https://test1.01yingxiao.com/admin-api/v2pay/apimerchant";
        } else {
            //url = "https://oa.cmzg.vip/api/order/pay/wx";
            url = "https://gateway.cmxz.com.cn/oa/api/order/pay/wx";
        }

        HashMap<String, Object> postmap = new HashMap<>();
        postmap.put("aid", inmap.get("aid2").toString());
        postmap.put("pid", inmap.get("pid2").toString());

        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, postmap, String.class);
        } catch (Exception e) {
            log.info("异常");
        }


        String confighttp = responseEntity.getBody();
        MallConfigSimple mallConfigSimple = JSON.parseObject(confighttp, MallConfigSimple.class);
        return mallConfigSimple;
    }

    //以调用方为准还是 get...
    //php提供方 show return 为止
    //
    public HashMap<String, String> getTidbys39(String s39like) {
        String url = "https://back.screen.cmxz.com.cn/index.php/gettidby39like?s39likekey=" + s39like;
        //      String url = "http://121.40.150.13:1112/index.php/gettidby39like?s39likekey=" + s39like;
        ResponseEntity<HashMap> responseEntity = null;
        try {
            responseEntity = restTemplate.getForEntity(url, HashMap.class);
        } catch (Exception e) {
            log.info("异常");
        }
        return responseEntity.getBody();

    }

    //查询接口OA的退款状态
    public String findoaRS() {

        Map<String, String> params = new HashMap<>();
        params.put("cmzgrefundstatus", "0");
        params.put("cmzgrefundreason", "测试");
        params.put("cmzgrefundnickname", "Q");
        params.put("cmzgrefundavatar", "https://tuan.cmzg.vip/images/water_salegroup3/20250114155934_6336971169_6786.jpeg");
        params.put("cmzgrefundtime", "1736920983642");
        params.put("cmzgrefundcustomercover", "https://tuan.cmzg.vip/images/water_salegroup3/20250114155934_6336971169_6786.jpeg");
        params.put("cmzgrefundcustomernickname", "12");
        params.put("cmzgrefundcustomermoney", "0.01");
        params.put("cmzgrefundcustomermobile", "18912713020");
        params.put("cmzgrefundcustomerregimentHead", "团长");
        params.put("cmzgrefundcustomernum", "0");
        params.put("cmzgrefundcustomerhasnum", "0");
        params.put("cmzgrefundcustomerrecommend", "0");
        params.put("cmzgrefundcustomerresponse", "0");

        StringBuilder encodedParams = new StringBuilder();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (encodedParams.length() > 0) {
                    encodedParams.append("&");
                }
                encodedParams.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                encodedParams.append("=");
                encodedParams.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //System.out.println(encodedParams.toString());
        return encodedParams.toString();
    }

    public void toNotifyOA(String appId, String aid, String pid, String orderNo, String fee, String openid, String status, String reject) {
        Map<String, String> params = new HashMap<>();
        params.put("cmzgrefundstatus", status);
        params.put("cmzgrefundreject", reject);
        String datajosn = JSON.toJSONString(params);
        String esjson = null;
        try {
            esjson = URLEncoder.encode(datajosn, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        StringBuilder encodedParams = new StringBuilder();
//        try {
//            for (Map.Entry<String, String> entry : params.entrySet()) {
//                if (encodedParams.length() > 0) {
//                    encodedParams.append("&");
//                }
//                encodedParams.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
//                encodedParams.append("=");
//                encodedParams.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
//            }
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        //System.out.println(encodedParams.toString());
        //String es = encodedParams.toString();

        String url = "https://cm.cmzg.vip/app/index.php?i=" +
                pid + "&t=0&v=v1.0.0&from=wxapp&c=entry&a=wxapp&do=api_record_data_set&m=water_salegroup3&themeid=" +
                aid + "&recordid=" +
                orderNo + "&openid=" +
                openid + "&data=" +
                esjson;
        log.info("OA设置的urlxxx {}", url);
        ////

        String message = OkHttpUtils.builder().url(url)
                // 有参数的话添加参数，可多个
                //.addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                .async();

//        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
//        responseEntity.getBody();
    }



    @PermitAll
    @RequestMapping("/apiFindOrderBytid2")
    public String apiFindOrderBytid2(String tid2) {
        log.info("apiFindOrderBytid2+ {}", tid2);
        Integer dbw2_detailid = findOrderBytid2(tid2);
        //360654 是从W2查出来的; 夏天的OA新订单是没有的
        return dbw2_detailid+"";
    }

    public Integer findOrderBytid2(String dbtid2) {
        String url = "https://back.screen.cmxz.com.cn/index.php/findOrderBytid2?tid2=" + dbtid2;
        //   String url = "http://121.40.150.13:1112/index.php/gettidby39like?s39likekey=" + s39like;
        try {
//            URI uri = UriComponentsBuilder.fromUriString("https://back.screen.cmxz.com.cn/index.php/findOrderBytid2")
//                    .queryParam("tid2", dbtid2)
//                    .build()
//                    .toUri();
//            ResponseEntity<HashMap> responseEntity = restTemplate.getForEntity(uri, HashMap.class);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("ss：{}", responseEntity.getBody());
            String name = responseEntity.getClass().getName();

            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(responseEntity.getBody());

            // 直接读取可能的双层JSON


            if (jsonNode.isTextual()) { // 如果它是文本，说明可能是再次序列化的JSON
                String actualJson = jsonNode.asText();
                jsonNode = mapper.readTree(actualJson); // 再解析一次
            }

            if (jsonNode.has("id")) {
                int id = jsonNode.get("id").asInt();
                System.out.println("ID: " + id);
            } else {
                System.out.println("JSON does not contain 'id' field.");
            }

            if (jsonNode.has("detailid")) {
                int detailid = jsonNode.get("detailid").asInt();
                System.out.println("detailid: " + detailid);
                return detailid;
            } else {
                System.out.println("JSON does not contain 'id' field.");
            }


            return null;
        } catch (Exception e) {
            log.info("异常");
        }
        return null;
    }

}
